package com.xyy.saas.payment.adpater.config;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.xyy.saas.payment.adpater.channel.setting.ChannelConfig;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.cores.enums.ChannelEnum;
import com.xyy.saas.payment.util.ApolloUtil;
import com.xyy.saas.payment.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author wangtianqi
 * @date 2020/11/26 11:11
 */

@Slf4j
@Component
@DependsOn("apolloUtil")
public class ChannelConfigManager implements InitializingBean {

    private List<ChannelConfig> channelConfigs = JSONUtils.parse2List(ApolloUtil.getProperty(Constants.CHANNEL_CONFIG), ChannelConfig.class);

    public String checkRoute(String businessOrderType, String payChannel) {
        return getAdapterName(payChannel);
    }

    public String getAdapterName(String channel) {
        if (Constants.thirdChannelSubmitPingan(channel)) {
            return Constants.transThirdCahnnelSubmitPingan(channel);
        }
        if(channel.contains(ChannelEnum.WX.getCode())) {
          return Constants.CHANNEL_DIRECT_NAME_WX;
        }
        if(channel.contains(ChannelEnum.ALIPAY.getCode())) {
            return Constants.CHANNEL_DIRECT_NAME_ALIPAY;
        }
        // 下单时候走哪个都行
        if(channel.equals(Constants.CHANNEL_AGGREGATE_NAME)) {
            return  Constants.CHANNEL_DIRECT_NAME_WX;
        }
        if(channel.contains(Constants.CHANNEL_UNIONPAY_NAME)) {
            return  Constants.CHANNEL_UNIONPAY_NAME;
        }
        return Constants.CHANNEL_AGGREGATE_NAME;
    }

    private boolean isSame(ChannelConfig c1, ChannelConfig c2) {
        return c1.toString().equals(c2.toString());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Set set = new HashSet();
        set.add(Constants.CHANNEL_CONFIG);
        //动态监听配置变化
        Config config = ConfigService.getAppConfig();
        config.addChangeListener(new ConfigChangeListener() {
            @Override
            public void onChange(ConfigChangeEvent changeEvent) {
                List<ChannelConfig> newConfigs = JSONUtils.parse2List(ApolloUtil.getProperty(Constants.CHANNEL_CONFIG), ChannelConfig.class);
                if(newConfigs != null && !newConfigs.isEmpty()) {
                    channelConfigs = newConfigs;
                    log.info("ChannelConfigManager#onChange change configs success channelConfigs:{}" , JSONUtils.toJSON(channelConfigs));
                }
            }
        }, set);
    }
}
